// 以类的方式去写，比较便于最终扩展

class Request {
    constructor(config) {
        let defConf = {
            origin: '',
            uri_maps: [],
        };
        this.err_code = {};
        this.config = config;
        // 公共 headers
        this.headers = {};
        this.queue = new Set();
        // 存储放前route对象
        this.route = null;
    }

    getCurPage() {
        // 据图如何获取看情况
        return this.route.name;
    }

    // 根据 origin url 获取到最终 url
    resolveUri(url) { }

    // 将 query 对象转为字符串
    formatQuery(query) {
        return ''
    }

    run({ method, headers, data, query }) {
        // 要获取当前页的name
        let cur = this.getCurPage();
        let resolveFn = null;
        let rejectFn = null;
        let pro = new Promise((resolve, reject) => {
            resolveFn = resolve;
            rejectFn = reject;
        });
        let headers = Object.assign({}, headers, this.headers);

        let xhr = new XMLHttpRequest();

        xhr.open(method, this.resolveUri(url, query), true);

        Object.keys(headers).forEach(key => {
            xhr.setRequestHeaders(key, headers[key]);
        });

        xhr.send(data);

        xhr.onload = function (e) {
            if (this.status >= 200 && this.status < 300 || this.status == 304) {
                let value = this.responseText;
                try {
                    value = JSON.stringify(value);
                } catch (e) {
                    rejectFn(e);
                }
            }else{
                // 请求失败，做 提示处理
            }
        }

        // 进度
        xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
                req.progressHandler && req.progressHandler(e.loaded, e.total);
            }
        }

        xhr.ontimeout = xhr.onerror = function (e) {
            // 打点
            // 是否应该自己部一个简单的打点服务器
            resolveFn({
                type: 'error',
                e
            });
        }

        xhr.onabort = function (e) {
            resolveFn({
                type: 'abort',
                e
            });
        }

        pro.progress = function (cb) {
            this.progressHandler = cb;
            // 继续将 promise 向下传递
            return req;
        }

        return pro;
    }

    get(config) {

    }

    post() {

    }
}